# -- coding: utf-8 --
import sys
import io

# 设置标准输出的编码为UTF-8
if sys.stdout.encoding != "UTF-8":
    sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8", errors="replace")
# DeepSeek AI对话 - 优化网络稳定性
import requests
import os
import json
import time
from dotenv import load_dotenv

print("=== DeepSeek AI对话系统（优化版） ===")


def load_environment():
    """加载环境变量"""
    load_dotenv()
    api_key = os.getenv("DEEPSEEK_API_KEY")

    if not api_key:
        print("❌ 未找到DEEPSEEK_API_KEY")
        return None

    print(f"✅ API Key加载成功: {api_key[:10]}...")
    return api_key


def deepseek_chat_with_retry(message, conversation_history, api_key, max_retries=3):
    """带重试机制的DeepSeek API调用"""

    url = "https://api.deepseek.com/chat/completions"

    headers = {"Content-Type": "application/json", "Authorization": f"Bearer {api_key}"}

    # 构建消息历史
    messages = conversation_history + [{"role": "user", "content": message}]

    payload = {
        "model": "deepseek-chat",
        "messages": messages,
        "stream": False,
        "max_tokens": 1000,
        "temperature": 0.7,
    }

    for attempt in range(max_retries):
        try:
            print(f"🔄 请求尝试 {attempt + 1}/{max_retries}...")

            response = requests.post(url, headers=headers, json=payload, timeout=30)

            print(f"状态码: {response.status_code}")

            if response.status_code == 200:
                result = response.json()
                ai_response = result["choices"][0]["message"]["content"]

                # 更新对话历史
                updated_history = messages + [
                    {"role": "assistant", "content": ai_response}
                ]

                # 限制历史记录长度
                if len(updated_history) > 10:
                    updated_history = updated_history[-10:]

                print("✅ 请求成功！")
                return ai_response, updated_history

            elif response.status_code == 429:
                wait_time = 10  # 频率限制，等待10秒
                print(f"⏳ 频率限制，等待{wait_time}秒...")
                time.sleep(wait_time)
                continue

            else:
                error_info = response.text
                print(f"❌ API错误 {response.status_code}: {error_info}")
                return f"API错误: {response.status_code}", conversation_history

        except requests.exceptions.Timeout:
            print(f"❌ 请求超时，尝试 {attempt + 1}/{max_retries}")
            if attempt < max_retries - 1:
                wait_time = 5 * (attempt + 1)  # 递增等待时间
                print(f"⏳ 等待{wait_time}秒后重试...")
                time.sleep(wait_time)
            continue

        except requests.exceptions.ConnectionError:
            print(f"❌ 连接错误，尝试 {attempt + 1}/{max_retries}")
            if attempt < max_retries - 1:
                wait_time = 3 * (attempt + 1)
                print(f"⏳ 等待{wait_time}秒后重试...")
                time.sleep(wait_time)
            continue

        except Exception as e:
            print(f"❌ 其他错误: {e}")
            return f"请求失败: {e}", conversation_history

    return "❌ 所有重试都失败了，请检查网络连接", conversation_history


def show_conversation_stats(history):
    """显示对话统计"""
    user_msgs = [msg for msg in history if msg["role"] == "user"]
    assistant_msgs = [msg for msg in history if msg["role"] == "assistant"]

    print(f"📊 对话统计: {len(user_msgs)}轮对话 | 历史记录: {len(history)}条消息")


def interactive_chat_optimized():
    """优化的交互式对话"""
    # api_key = load_environment()
    # if not api_key:
    #     return

    print("\n💬 DeepSeek AI对话开始（优化版）")
    print("=" * 60)
    print("可用命令:")
    print("  /history - 显示对话历史")
    print("  /clear   - 清空对话历史")
    print("  /stats   - 显示统计信息")
    print("  /exit    - 退出程序")
    print("=" * 60)

    conversation_history = []

    while True:
        try:
            user_input = input("\n👤 我: ").strip()

            if user_input.lower() in ["/exit", "退出", "exit", "quit"]:
                print("再见！👋")
                break

            elif user_input.lower() == "/history":
                print("\n📝 对话历史:")
                for i, msg in enumerate(conversation_history, 1):
                    role_icon = "👤" if msg["role"] == "user" else "🤖"
                    preview = (
                        msg["content"][:50] + "..."
                        if len(msg["content"]) > 50
                        else msg["content"]
                    )
                    print(f"{i}. {role_icon} {preview}")
                continue

            elif user_input.lower() == "/clear":
                conversation_history = []
                print("🗑️ 对话历史已清空")
                continue

            elif user_input.lower() == "/stats":
                show_conversation_stats(conversation_history)
                continue

            elif not user_input:
                continue

            # 处理正常对话
            start_time = time.time()
            response, conversation_history = deepseek_chat_with_retry(
                user_input, conversation_history, api_key
            )
            response_time = time.time() - start_time

            print(f"🤖 AI: {response}")
            print(f"⏱️ 响应时间: {response_time:.2f}秒")
            show_conversation_stats(conversation_history)

        except KeyboardInterrupt:
            print("\n\n程序被用户中断")
            break
        except Exception as e:
            print(f"\n❌ 程序错误: {e}")


def test_continuous_dialogue():
    """测试连续对话能力"""
    # api_key = load_environment()
    # if not api_key:
    #     return

    print("\n🚀 测试连续对话能力")
    print("=" * 50)

    conversation_history = []

    test_scenarios = [
        "你好，请叫我学习助手",
        "请记住我最喜欢的编程语言是Python",
        "我之前告诉你我最喜欢什么编程语言？",
        "基于我的喜好，推荐一个Python学习项目",
        "谢谢你的帮助！",
    ]

    for i, scenario in enumerate(test_scenarios, 1):
        print(f"\n【场景 {i}】")
        print(f"👤 我: {scenario}")

        response, conversation_history = deepseek_chat_with_retry(
            scenario, conversation_history, api_key
        )
        print(f"🤖 AI: {response}")
        print(f"📈 历史记录: {len(conversation_history)}条消息")
        print("-" * 50)

        # 稍微延迟，避免请求过快
        time.sleep(2)


if __name__ == "__main__":
    api_key = load_environment()
    if not api_key:
        exit()

    print("\n选择运行模式:")
    print("1. 测试连续对话")
    print("2. 交互对话（推荐）")

    choice = input("请输入选择 (1 或 2): ").strip()

    if choice == "1":
        test_continuous_dialogue()
    else:
        interactive_chat_optimized()
